<template>
  <el-card class="mt-10">
    <el-form label-width="120px" :rules="rules" ref="skuForm" :model="formData">
      <el-form-item label="SPU名称">
        <span>{{ spuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="SKU名称" v-model="formData.skuName" />
      </el-form-item>
      <el-form-item label="价格（元）" prop="price">
        <el-input type="number" v-model="formData.price" />
      </el-form-item>
      <el-form-item label="重量（千克）" prop="weight">
        <el-input type="number" v-model="formData.weight" />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input type="textarea" v-model="formData.skuDesc" />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-form-item
          v-for="(attrInfo, index) in attrInfoList"
          :label="attrInfo.attrName"
          :key="attrInfo.id"
          class="mb-10"
        >
          <el-select v-model="formData.skuAttrValueList[index]">
            <el-option
              v-for="attrValue in attrInfo.attrValueList"
              :key="attrValue.id"
              :value="`${attrInfo.id}:${attrInfo.attrName}:${attrValue.id}:${attrValue.valueName}`"
              :label="attrValue.valueName"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-form-item
          class="mb-10"
          v-for="(saleAttr, index) in saleAttrList"
          :key="saleAttr.id"
          :label="saleAttr.saleAttrName"
        >
          <el-select v-model="formData.skuSaleAttrValueList[index]">
            <!--  -->
            <el-option
              v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              :label="saleAttrValue.saleAttrValueName"
              :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table :data="imgList" border @selection-change="selectionHandle">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="图片">
            <template #default="{ row }">
              <img :src="row.imgUrl" alt="row.imgName" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="setDefaultImg(row)"
                v-if="row.isDefault !== '1'"
                >设为默认</el-button
              >
              <el-tag type="success" v-else>默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item prop="skuDefaultImg"></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSkuInfo">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'addSku',
}
</script>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { useCategoryId } from '@/stores/categoryId'
import {
  getAttrInfoListApi,
  getSpuSaleAttrList,
  getSpuImageList,
  saveSkuInfoApi,
} from '@/api/product/SPUApi'
import { getSpuSaleAttrListApi } from '@/api/product/skuApi'

import type { FormInstance, FormRules } from 'element-plus'
import type {
  AttrInfoList,
  SpuSaleAttrListType,
  SPUParamsType2,
  SaveSkuInfoParams2,
  SkuImageItem,
  SkuImageList,
} from '@/api/product/model/SPUType'
import { ElMessage } from 'element-plus'

// 取消按钮
const goBack = () => {
  emit('changeCom', 0)
  emit('showSkuList', true)
}
// 表单验证-----------------------------------------------------开始
const skuForm = ref<FormInstance>() // 表单实例

const imgValidator = (rule: any, value: any, callback: any) => {
  // console.log(value)
  if (!value.length) {
    callback(new Error('请选择SKU图片'))
    return
  }
  if (!value.some((img: any) => img.isDefault === '1')) {
    callback(new Error('请从所选图片中设置默认图片'))
  }
  callback()
}
const triggerForm = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback(new Error('请至少选择一个属性'))
    return
  }
  callback()
}
const rules = reactive<FormRules>({
  skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  weight: [
    { required: true, message: '请输入商品重量（千克）', trigger: 'blur' },
  ],
  skuDesc: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  skuAttrValueList: [
    {
      required: true,
      validator: triggerForm,
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      validator: triggerForm,
    },
  ],
  skuImageList: [{ required: true, validator: imgValidator }],
})
// 获取三级分类id仓库
const categoryId = useCategoryId()

// 收集表单数据
const formData = reactive<SaveSkuInfoParams2>({
  category3Id: categoryId.category3Id as number,
  id: undefined,
  price: '0',
  skuName: '',
  spuId: 0,
  weight: '0',
  skuDefaultImg: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
})
// 选择图片的回调
const selectionHandle = (row: SkuImageList) => {
  formData.skuImageList = row
}
// 表单提交
const submitSkuInfo = () => {
  // ElMessage.success('提交成功')
  skuForm.value?.validate(async (valid) => {
    if (valid) {
      await saveSkuInfoApi({
        ...formData,
        spuId: prop.spuInfo.id as number,
        skuAttrValueList: formData.skuAttrValueList
          .filter(Boolean)
          .map((attr) => {
            const [attrId, attrName, valueId, valueName] = attr.split(':')
            return { attrId: +attrId, attrName, valueId: +valueId, valueName }
          }),

        skuSaleAttrValueList: formData.skuSaleAttrValueList
          .filter(Boolean)
          .map((attrValue) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = attrValue.split(':')
            return {
              saleAttrId: +saleAttrId,
              saleAttrName,
              saleAttrValueId: +saleAttrValueId,
              saleAttrValueName,
            }
          }),
      })
      ElMessage.success('提交成功')
      emit('changeCom', 0)
    }
  })
}
// 定义商品基础属性数据
const attrInfoList = ref<AttrInfoList>([])
// 定义销售属性数据
const saleAttrList = ref<SpuSaleAttrListType[]>([])
// 定义图片列表数据
const imgList = ref<SkuImageList>([])
// 组件挂载请求数据
onMounted(async () => {
  if (categoryId.category3Id) {
    attrInfoList.value = await getAttrInfoListApi(
      categoryId.category1Id as number,
      categoryId.category2Id as number,
      categoryId.category3Id as number
    )
    return
  }
})
onMounted(async () => {
  saleAttrList.value = await getSpuSaleAttrList(prop.spuInfo.id as number)
})
onMounted(async () => {
  // 请求图片数据
  imgList.value = await getSpuImageList(prop.spuInfo.id as number)
})
// 设置默认图片
const setDefaultImg = (row: SkuImageItem) => {
  imgList.value.forEach((img) => (img.isDefault = '0'))
  row.isDefault = '1'
  formData.skuDefaultImg = row.imgUrl
}
// 获取自定义事件
const emit = defineEmits(['changeCom', 'showSkuList'])
// 获取spuName
const prop = defineProps<{ spuInfo: SPUParamsType2 }>()

// 监视spuInfo数据变化
watch(prop.spuInfo, (val) => {
  console.log(val)
})
</script>

<style scoped>
.mb-10 {
  margin-bottom: 10px;
}
.sku-img {
  height: 100px;
}
</style>
<style></style>
